package controllers

import (
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	"log"
	"net/http"
)

type IWsTestController interface {
	handleWebSocket()
}
type WsTestController struct{}

func NewWsTestController() *WsTestController {
	return &WsTestController{}
}

// 定义 WebSocket 升级器，用于将 HTTP 连接升级为 WebSocket 连接
var upgrader = websocket.Upgrader{
	ReadBufferSize:  1024,
	WriteBufferSize: 1024,
	CheckOrigin: func(r *http.Request) bool {
		// 允许所有来源的跨域请求，生产环境中根据需要调整
		return true
	},
}

func (wsc WsTestController) HandleWebSocket(c *gin.Context) {
	// 将 HTTP 连接升级为 WebSocket 连接
	ws, err := upgrader.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		log.Println("升级为 WebSocket 连接失败:", err)
		return
	}
	defer ws.Close()

	for {
		// 读取消息
		messageType, message, err := ws.ReadMessage()
		if err != nil {
			log.Println("读取消息失败:", err)
			break
		}

		log.Printf("收到消息: %s", message)

		// 将收到的消息回显给客户端
		err = ws.WriteMessage(messageType, message)
		if err != nil {
			log.Println("发送消息失败:", err)
			break
		}
	}
}
